package com.niodata.dt.fs;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.hadoop.fs.FSInputStream;

public class LocalFsInputStream extends FSInputStream {
  private long pos;
  private FileInputStream inputStream;
  private final File file;
  private final long length;

  public LocalFsInputStream(File file, FileInputStream inputStream) {
    this.inputStream = inputStream;
    this.file = file;
    this.length = this.file.length();
  }

  @Override
  public void seek(long pos) throws IOException {
    if (pos >= length) {
      throw new IOException("EOF");
    }
    if (this.pos < pos) {
      long n = pos - this.pos;
      long n1 = this.inputStream.skip(n);
      if (n != n1) {
        throw new IOException("stream skip failed");
      }
      this.pos = pos;
    } else {
      inputStream.close();
      inputStream = new FileInputStream(file);
      inputStream.skip(pos);
      this.pos = pos;
    }
  }

  @Override
  public long getPos() throws IOException {
    return this.pos;
  }

  @Override
  public boolean seekToNewSource(long targetPos) throws IOException {
    return false;
  }

  @Override
  public int read() throws IOException {
    int b = inputStream.read();
    pos++;
    return b;
  }
}
